<template>
  <div>
    <div class="search-container">
      <div class="search-inp-container">
        <el-input @keyup.enter.native="handleSearch" placeholder="输入标题" v-model="listQuery.title" clearable>
        </el-input>
      </div>
      <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
      <el-button class="search-btn" type="primary" icon="el-icon-plus" v-if="mall_ad_add" @click="handleAdd">添加</el-button>
      <el-button class="search-btn" :autofocus="true" icon="el-icon-refresh" @click="refreshHandle">刷新</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row>
      <el-table-column align="center" prop="title" label="标题" width="80">
      </el-table-column>
      <el-table-column align="center" prop="imgUrl" label="图片" width="180">
        <template   slot-scope="scope">
          <img :src="scope.row.imgUrl"  min-width="70" height="70" />
        </template>

      </el-table-column>
      <!--<el-table-column align="center" prop="type"  label="跳转类型">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="跳转类型">
        <template slot-scope="scope">
          <span >
            {{scope.row.type | gotoTypeFilter}}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="href" label="跳转id/链接">
      </el-table-column>
      <el-table-column align="center"  label="是否显示">
        <template slot-scope="scope">
          <span v-if="scope.row.isShow == 1">
            {{scope.row.isShow | statusFilter}}
          </span>
          <span v-else type="danger">
            {{scope.row.isShow | statusFilter}}
          </span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="180" v-if="mall_ad_del  || mall_ad_update ">
        <template align="center"  slot-scope="scope">
          <el-button v-if="mall_ad_update" size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="mall_ad_del" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current" :page-size="listQuery.size" :page-sizes="[10, 40, 80, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" enctype="multipart/form-data" >
        <el-form-item label="图片" >
          <div>
            <el-upload
              class="avatar-uploader1"
              :action="imgUpload"
              :headers = "headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar1" >
              <i v-else class="el-icon-plus avatar-uploader-icon1" style="border: 1px dashed #d9d9d9;"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item class="w347"  label="标题" placeholder="请输入标题" prop="title">
          <el-input  v-model="form.title" maxLength='12'></el-input>
        </el-form-item>

        <el-form-item label="跳转方式" prop="type" >
          <el-select class="filter-item w347" v-model="form.type" placeholder="请选择" @change="changeType(form.type)">
            <el-option v-for="item in recomMaps" :key="item.key" :label="item.name" :value="item.key" >
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="this.typeLable" prop="href" v-if="typeShow">
          <el-input class="w347" v-model="form.href" placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="是否显示"  prop="isShow">
          <el-select class="filter-item w347" v-model="form.isShow" placeholder="请选择" >
            <el-option v-for="item in isShowOptions" :key="item.value" :label="item.dictDesc" :value="item.value" :disabled="isDisabled[item.delFlag]" >
              <span style="float: left">{{ item.dictDesc }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input class="w347" type="number" v-model="form.sort" placeholder="" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
        </el-form-item>

        <!--<el-form-item label="推送行社" prop="orgNo">-->
        <!--<el-select class="filter-item w347" v-model="form.orgNo" placeholder="请选择" >-->
        <!--<el-option v-for="item in orgOptions" :key="item.orgId" :label="item.orgName" :value="item.orgId" >-->
        <!--<span style="float: left">{{ item.orgName }}</span>-->
        <!--</el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetchList, delObj, getObj, addObj, putObj, uploadImg, getToken,getFileTypeISPic } from '@/api/ad'
  import { getTopDictListByDescNew } from '@/api/dict'
  import { mapGetters } from 'vuex'
  export default {
    data() {
      return {
        imageUrl: '',
        tableKey: 0,
        listLoading: false,
        list: [],
        orgOptions: [],
        listQuery: {
          current: 1,
          size: 10,
          title: '',
          //desc: 'create_date'
        },
        total: 0,
        mall_ad_add: false,
        mall_ad_update: false,
        mall_ad_del: false,
        sys_user_select: false,
        dialogFormVisible: false,
        typeLable: '商品ID',
        typeShow: true,
        // 图片
        dialogImageUrl: undefined,
        dialogVisible: false,
        fileList: [],
        url: '',
        // imgUpload: 'http://127.0.0.1:2004/mall/ad/imgUpload/',
        imgUpload: process.env.BASE_API + '/mall/ad/imgUpload/',
        headers: {
          'Authorization': getToken()
          // token为系统访问需要的,放在header中
        },
        isMultiple: false,
        imgLimit: 1,
        // 图片
        form: {
          title: undefined,
          type: undefined,
          href: undefined,
          isShow: undefined,
          sort: undefined,
          imgUrl: undefined,
          orgNo: undefined
        },
        recomMaps: [

          {
            key: '2',
            name: '跳转商品'
          },
          {
            key: '4',
            name: '跳转商户'
          },
          {
            key: '5',
            name: '跳转链接'
          },
          {
            key: '9',
            name: '无'
          }
        ],
        rules: {
          title: [
            {
              required: true,
              message: '请输入标题',
              trigger: 'blur'
            }
          ],
          type: [
            {
              required: true,
              message: '请选择类型',
              trigger: 'change'
            }
          ],
          href: [
            {
              required: true,
              message: '不能为空',
              trigger: 'blur'
            }
          ],
          isShow: [
            {
              required: true,
              message: '请选择是否显示',
              trigger: 'change'
            }
          ],
          sort: [
            {
              required: true,
              message: '排序不能为空',
              trigger: 'blur'
            }
          ],
          /* orgNo: [
             {
               required: true,
               message: '请选择推送行社',
               trigger: 'blur'
             }
           ]*/
        },
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogStatus: '',
        role: [],
        typeOptions: [],
        isShowOptions: [],
        isDisabled: {
          0: false,
          1: true
        },
        statusOptions: ['0', '1'],
        dialogDeptVisible: false,
        treeDeptData: [],
        checkedKeys: [],
        defaultProps: {
          children: 'childrens',
          label: 'name'
        }
      }
    },

    components: {},
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: '否',
          1: '是',
          9: '锁定'
        }
        return statusMap[status]
      },
      gotoTypeFilter(status) {
        const statusMap = {
          // 1: '跳转网点好礼',
          2: '跳转商品',//原电子券
          //3: '跳转活动',
          4: '跳转商铺',
          5: '链接',
          9: '无'
        }
        return statusMap[status]
      }
    },
    computed: {
      ...mapGetters(['permissions'])
    },

    mounted() {
      this.getList()
      this.mall_ad_add = this.permissions['/mall/ad:add']
      this.mall_ad_update = this.permissions['/mall/ad:update']
      this.mall_ad_del = this.permissions['/mall/ad:del']
      this.sys_user_select = this.permissions['/admin/user:select']
    },

    methods: {
      getList() {
        this.listLoading = true
        this.listQuery.isAsc = false
        fetchList(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },

      refreshHandle() {
        this.listQuery.current = 1
        this.listQuery.size = 10
        this.listQuery.username = ''
        this.getList()
      },
      handleAdd() {
        this.form = {}
        this.imageUrl = ''
        this.dialogStatus = 'create'
        this.getDictList()
        //this.getOrgList()
        this.dialogFormVisible = true
      },
      handleDelete(row) {
        this.$confirm(
          '此操作将永久删除该广告, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          delObj(row.adId)
            .then(() => {
              this.getList()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
            .cache(() => {
              this.$notify({
                title: '失败',
                message: '删除失败',
                type: 'error',
                duration: 2000
              })
            })
        })
      },
      handleEdit(row) {
        this.dialogStatus = 'update'
        this.getDictList()
        //this.getOrgList()
        this.form = {}
        this.imageUrl = ''
        getObj(row.adId).then(response => {
          this.form = response.data
          // 图片回显
          const obj = new Object()
          obj.url = response.data.imgUrl
          if (obj.url != null) {
            this.imageUrl = obj.url
          }
          if ( this.form.type == 2) {
            this.typeLable = '商品ID'
            this.typeShow = true
          } else if (this.form.type == 5) {
            this.typeLable = '链接'
            this.typeShow = true
          } else if (this.form.type == 4) {
            this.typeLable = '商户ID'
            this.typeShow = true
          } else if (this.form.type == 9) {
            this.typeShow = false
          }
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
        })
      },
      handleSearch() {
        this.listQuery.current = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.getList()
      },
      create(formName) {
        if (this.imageUrl === '') {
          this.$notify({
            title: '失败',
            message: '请上传图片',
            type: 'error',
            duration: 2000
          })
          return
        }
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      cancel(formName) {
        this.dialogFormVisible = false
        this.$refs[formName].resetFields()
      },
      update(formName) {
        if (this.imageUrl === '') {
          this.$notify({
            title: '失败',
            message: '请上传图片',
            type: 'error',
            duration: 2000
          })
          return
        }
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false
            this.form.password = undefined
            putObj(this.form).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      async getDictList() {
        const res = await getTopDictListByDescNew('跳转类型')
        this.typeOptions = res.data
        const res1 = await getTopDictListByDescNew('是否')
        this.isShowOptions = res1.data
      },
      async getOrgList() {
        const res = await fetchOrgList()
        this.orgOptions = res.data
      },

      handleAvatarSuccess(res, file) {
        var url = res.true
        if (url == '' || url == undefined || url == 'undefined') {
          this.$notify({
            title: '失败',
            message:res.false,
            type: 'error',
            duration: 2000
          })
          return
        }
        this.form.imgUrl = url// 表单提交
        this.imageUrl = URL.createObjectURL(file.raw)
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      },

      changeType(e) {
        if (e == 2) {
          this.typeLable = '商品ID'
          this.typeShow = true
        } else if (e == 5) {
          this.typeLable = '链接'
          this.typeShow = true
        }  else if (e == 4) {
          this.typeLable = '商户ID'
          this.typeShow = true
        } else if (e == 9) {
          this.typeShow = false
          this.form.href =""
        }
      }

    }
  }

</script>


<style lang='scss' scoped>
  .w347 {
    width: 100%;
  }
  .avatar-uploader1 .el-upload1 {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader1 .el-upload:hover1 {
    border-color: #409EFF;
  }
  .avatar-uploader-icon1 {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar1 {
    width: 200px;
    height: 178px;
    display: block;
  }
</style>

